<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use think\facade\Cache;
use think\facade\Event;

class Account extends Base
{
    protected $name = 'user_account';

    protected function user(): object
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,photo');
    }

    protected function take(): object
    {
        return $this->hasOne(User::class, 'id', 'source')
            ->field('id,code,nickname,mobile,photo');
    }

    protected function getTypeAttr($value): string
    {
        return get_pay_way($value);
    }

    /**
     * 奖金入账
     */
    public static function bonusEntry($uid, $amount, $intro, $source, $category, $orderId): bool|string
    {
        try {
            $user = User::find($uid);
            if ($amount > 0 && !empty($uid) && $user->is_active == 2) {
                $system = Cache::get('system');
                $greenAmount = round($amount * $system['green_rate'], 2);
                $couponAmount = round($amount - $greenAmount, 2);
                Target::Account()->basics($uid, 'green', $greenAmount, $intro, '+')->setProtoAmount($amount)->setOrderId($orderId)->createBonus($source, $category);
                Target::Account()->basics($uid, 'coupon', $couponAmount, $intro, '+')->setProtoAmount($amount)->setOrderId($orderId)->createNormal($source);

                Event::trigger('Statistics', ['key' => 'expend', 'value' => $amount]);
                $content = "您获得【{$intro}】【{$amount}】元，已发放至您的账户余额，请注意查收。";
                UserNotify::add(1, $uid, $intro . '-收益到账', $content);

                if($category == 1){
                    $user->platoon1_bonus += $amount;
                    if($user->platoon1_bonus >= Cache::get('system')['platoon_max_amount1']){
                        $user->out_1 = 1;
                    }
                    $user->save();
                }elseif($category == 2){
                    $user->platoon2_bonus += $amount;
                    if($user->platoon2_bonus >= Cache::get('system')['platoon_max_amount2']){
                        $user->out_2 = 1;
                    }
                    $user->save();
                }elseif($category == 3){
                    $user->platoon3_bonus += $amount;
                    if($user->platoon3_bonus >= Cache::get('system')['platoon_max_amount3']){
                        $user->out_3 = 1;
                    }
                    $user->save();
                }

            }

            return true;
        } catch (\Exception $e) {

            return $e->getMessage();
        }
    }
}